package org.example.servlet;

import org.example.Util.DataSourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/AdminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(AdminLoginServlet.class);
    private static final String ADMIN_KEY = "123456"; // 固定密钥

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("adminUsername");
        String password = request.getParameter("adminPassword");
        String adminKey = request.getParameter("adminKey");

        // 验证密钥
        if (!ADMIN_KEY.equals(adminKey)) {
            request.setAttribute("error", "管理员密钥不正确");
            request.getRequestDispatcher("Adminlogin.jsp").forward(request, response);
            return;
        }

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            // 获取数据库连接
            conn = DataSourceUtil.getDataSource().getConnection();

            // 查询管理员信息
            String sql = "SELECT id, username, password FROM admins WHERE username = ? AND is_active = TRUE";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            rs = stmt.executeQuery();

            if (rs.next()) {
                // 验证密码 (实际项目中应该使用加密验证)
                String storedPassword = rs.getString("password");

                if (password.equals(storedPassword)) {
                    // 登录成功，创建会话
                    HttpSession session = request.getSession();
                    session.setAttribute("adminUsername", username);
                    session.setAttribute("adminId", rs.getInt("id"));

                    // 更新最后登录时间
                    updateLastLogin(conn, rs.getInt("id"));

                    // 重定向到管理首页
                    response.sendRedirect("Managerindex.html");
                    return;
                }
            }

            // 登录失败
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("Adminlogin.jsp").forward(request, response);

        } catch (SQLException e) {
            logger.error("管理员登录数据库错误: {}", e.getMessage());
            request.setAttribute("error", "数据库错误，请稍后再试");
            request.getRequestDispatcher("Adminlogin.jsp").forward(request, response);
        } finally {
            // 关闭资源
            closeResources(rs, stmt, conn);
        }
    }

    private void updateLastLogin(Connection conn, int adminId) throws SQLException {
        String sql = "UPDATE admins SET last_login = CURRENT_TIMESTAMP WHERE id = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, adminId);
            stmt.executeUpdate();
        }
    }

    private void closeResources(ResultSet rs, PreparedStatement stmt, Connection conn) {
        try { if (rs != null) rs.close(); } catch (SQLException e) { logger.error("关闭ResultSet错误: {}", e.getMessage()); }
        try { if (stmt != null) stmt.close(); } catch (SQLException e) { logger.error("关闭PreparedStatement错误: {}", e.getMessage()); }
        try { if (conn != null) conn.close(); } catch (SQLException e) { logger.error("关闭Connection错误: {}", e.getMessage()); }
    }
}